export default defineComponent({
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    help: {
      type: String,
      default: $t("party9"),
    },
  },
  emits: ["update:modelValue"],
  setup(props, { attrs, emit, expose, slots }) {
    const loading = ref<boolean>(false);
    const beforeUpload = (file: any) => {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        message.error($t("base.onlySupportImage"));
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error($t("base.limit5MB"));
      }
      return isJpgOrPng && isLt5M;
    };
    const selfUpload = async (target: any) => {
      try {
        const formData = new FormData();
        loading.value = true;
        formData.append("avatar", target.file);
        const res: any = await userApi.uploadAvatar(formData);
        emit("update:modelValue", res?.data?.img_url);
        if (res.code != 200) return message.error(res.message);
        message.success(res.message);
      } catch (error: any) {
        message.error(error.message);
      } finally {
        loading.value = false;
      }
    };
    return () => (
      <>
        <a-upload
          accept="image/*"
          name="avatar"
          list-type="picture-card"
          show-upload-list={false}
          disabled={loading.value}
          beforeUpload={beforeUpload}
          customRequest={selfUpload}
        >
          {props.modelValue ? (
            <img src={props.modelValue} style="width: 100%; height: 100%" />
          ) : (
            <div>
              {loading.value ? (
                <loading-outlined />
              ) : (
                <>
                  <plus-outlined />
                  <div class="ant-upload-text">{props.help}</div>
                </>
              )}
            </div>
          )}
        </a-upload>
      </>
    );
  },
});
